package com.ujson.chat.client.controller;

import com.ujson.chat.client.command.ClientMenuConsoleCommand;
import com.ujson.chat.client.netty.NettyClient;
import com.ujson.chat.client.session.ClientSession;
import io.netty.channel.Channel;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Scanner;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * <h3>ujson-parent</h3>
 * <p>控制台命令控制器</p>
 *
 * @author JerryLiu  a1031757312@gmail.com
 * @version 1.0
 * @date 2021-11-22 21:58
 */
@Slf4j
@Data
@Service
public class CommandController {

    @Autowired
    private ClientMenuConsoleCommand menuConsoleCommand;

    @Autowired
    private NettyClient nettyClient;

    private Channel channel;
    private ClientSession clientSession;

    Scanner scanner;
    public void startThread() {
        scanner = new Scanner(System.in);
        while (true) {
            while (!this.isConnected()) {
                nettyClient.doConnection();
                this.waitConnect();
            }
            menuConsoleCommand.exec(scanner);
        }
    }

    private AtomicBoolean isConnected = new AtomicBoolean();
    public boolean isConnected() {
        return this.isConnected.get();
    }

    private Object connectLock = new Object();
    private AtomicBoolean connectFlag = new AtomicBoolean();
    public void waitConnect() {
        synchronized (connectLock) {
            try {
                connectFlag.getAndSet(true);
                while (connectFlag.get()) {
                    connectLock.wait();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public void notifyConnect() {
        synchronized (connectLock) {
            isConnected.getAndSet(true);
            connectFlag.set(false);
            connectLock.notifyAll();
        }
    }
}
